/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package han.wt.datingssite.controller;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author susan-elmar
 */
public class LoginFilter implements Filter{
    protected FilterConfig filterConfig;
    

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {        
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String userPath = req.getServletPath();        
        HttpSession session = req.getSession();
        String username = (String)session.getAttribute("username");
        System.out.println("userpath: " + userPath);
        
        //The client is not logged in!
        if(username == null){
            System.out.println("not logged in!");
            chain.doFilter(request, response);
        }
        //The user is logged in!
        else{
            System.out.println("Logged in!");
            if(userPath.equals("/register.jsp")){
                res.sendRedirect("./index.jsp");
            }
            else{
                chain.doFilter(request, response);
            }
        }
        
    }

    @Override
    public void destroy() {
        throw new UnsupportedOperationException("Not supported yet.");
    }
    
}
